package com.example.administrator.szb.util;

import android.app.Activity;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * Created by 了不起的潘
 * Created on 2017/12/19 19:04
 */


public class KeyboardChangListenerUitl {
    public interface KeyboardCallback{
        void doSomeThing();
    }


    /**
     *
     * @param activity
     */
    public static void KeyboardChangListener(Activity activity, final KeyboardCallback keyboardCallback){
        final View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rootView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isKeyboardShown(rootView)) {
                            //onKeyBoardShow();
                            //Toasts.show(LoginNewActivity_two.this, "ff", Toast.LENGTH_SHORT);

                            keyboardCallback.doSomeThing();


//                            作者：fish119
//                            链接：http://www.jianshu.com/p/6a9f979c7ba8
//                            來源：简书

                        } else {

                        }
                    }
                },0);

            }
        });
    }

    /**
     * 判断软键盘是否打开
     *
     * @param rootView 最上层布局
     * @return 打开：true，隐藏：false
     */
    private static boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }
}
